<template>
	<div class="chat-page" :style="{ height: documentHeight + 'px' }">
		<!-- 顶部导航 -->
		<div class="head-style row-ac" :style="{ width: documentWidth + 'px' }">
			<div class="row-ac text-white cursor-pointer" @click="goBack">
				<i class="iconfont icon-back2-01"></i>
				<span class="ml">{{ languageType === 'English' ? 'Back' : 'Geri' }}</span>
			</div>
		</div>
		<!-- 聊天消息展示 -->
		<ChatBoxVisitor :sessionId="sessionId" :chatHeight="localChatHeight" ref="chatBoxRef" />
		<!-- 底部输入框区域 -->
		<div class="chat-input-box row-ac" :style="{ width: documentWidth + 'px' }">
			<textarea ref="messageInput" v-model="messageText" @input="adjustHeight" @keydown.enter.prevent="onEnterKey"
				class="chat-textarea" placeholder="Type your message..." rows="1"></textarea>
			<button class="send-btn" @click="sendMessage">
				{{ languageType === 'English' ? 'Send' : 'Gönder' }}
			</button>
		</div>
	</div>
</template>

<script setup lang="ts">
	import { ref, onMounted, onUnmounted, nextTick } from "vue";
	import { useRoute, useRouter } from "vue-router";
	import ChatBoxVisitor from "~/components/ChatBoxVisitor.vue";

	const { post } = useFetchApi();
	const route = useRoute();
	const router = useRouter();

	const documentWidth = ref(0);
	const documentHeight = ref(0);
	const localChatHeight = ref(0); // ChatBox 高度
	const sessionId = ref("");
	const languageType = ref("English");

	const messageText = ref("");
	const messageInput = ref<HTMLTextAreaElement | null>(null);
	const chatBoxRef = ref<any>(null);

	// 计算父组件尺寸并更新 ChatBox 高度
	const updateDocumentSize = () => {
		documentWidth.value = window.innerWidth;
		documentHeight.value = window.innerHeight;
		const inputBoxHeight = 60; // 输入框高度
		const headHeight = 70;      // 头部高度
		localChatHeight.value = documentHeight.value - headHeight - inputBoxHeight;
		nextTick(() => {
			chatBoxRef.value?.scrollToBottom?.();
		});
	};

	// 调整输入框高度
	function adjustHeight() {
		const textarea = messageInput.value;
		if (!textarea) return;

		textarea.style.height = "auto";
		const style = window.getComputedStyle(textarea);
		const lineHeight = parseFloat(style.lineHeight || "20");
		const padding = parseFloat(style.paddingTop || "0") + parseFloat(style.paddingBottom || "0");
		const maxHeight = lineHeight * 3 + padding;

		const newHeight = Math.min(textarea.scrollHeight, maxHeight);
		textarea.style.height = newHeight + "px";

		// 输入框高度变化时更新 ChatBox 高度
		const headHeight = 70;
		const inputBoxHeight = textarea.offsetHeight;
		localChatHeight.value = documentHeight.value - headHeight - inputBoxHeight;
		nextTick(() => {
			chatBoxRef.value?.scrollToBottom?.();
		});
	}

	// Enter 键处理
	function onEnterKey(e : KeyboardEvent) {
		const textarea = messageInput.value;
		if (!textarea) return;

		if (e.shiftKey) {
			const start = textarea.selectionStart || 0;
			const end = textarea.selectionEnd || 0;
			messageText.value = messageText.value.slice(0, start) + "\n" + messageText.value.slice(end);
			nextTick(() => {
				textarea.selectionStart = textarea.selectionEnd = start + 1;
				adjustHeight();
			});
			return;
		}
		sendMessage();
	}

	// 发送消息
	async function sendMessage() {
		if (!messageText.value.trim()) return;
		try {
			const res = await post("/api/chat/create_messages", {
				session_id: sessionId.value,
				content: messageText.value,
				content_img: ""
			});
			console.log(res);
		} catch (err) {
			console.error(err);
		}
		messageText.value = "";
		await nextTick(() => {
			if (messageInput.value) messageInput.value.style.height = "auto";
			// 重置 ChatBox 高度
			const headHeight = 70;
			const inputBoxHeight = 60;
			localChatHeight.value = documentHeight.value - headHeight - inputBoxHeight;
			chatBoxRef.value?.scrollToBottom?.();
		});
	}

	// 返回
	function goBack() {
		router.back();
	}

	// 键盘弹出监听
	function handleViewportResize() {
		const vh = window.visualViewport?.height || window.innerHeight;
		documentHeight.value = vh;
		const inputBoxHeight = messageInput.value?.offsetHeight || 60;
		const headHeight = 70;
		localChatHeight.value = vh - headHeight - inputBoxHeight;
		nextTick(() => chatBoxRef.value?.scrollToBottom?.());
	}

	onMounted(() => {
		sessionId.value = route.params.sessionId as string;
		const savedLang = localStorage.getItem("languageType");
		if (savedLang) languageType.value = savedLang;

		updateDocumentSize();
		window.addEventListener("resize", updateDocumentSize);
		window.visualViewport?.addEventListener("resize", handleViewportResize);
	});

	onUnmounted(() => {
		window.removeEventListener("resize", updateDocumentSize);
		window.visualViewport?.removeEventListener("resize", handleViewportResize);
	});
</script>

<style scoped>
	.head-style {
		height: 70px;
		background: linear-gradient(135deg, #030d26 0%, #1a2a4a 100%);
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}

	.chat-input-box {
		height: 59px;
		border-top: 1px solid #ddd;
		background: #fff;
		display: flex;
		align-items: center;
	}

	.chat-textarea {
		flex: 1;
		resize: none;
		overflow-y: auto;
		padding: 8px 10px;
		border-radius: 3px;
		border: 1px solid #ccc;
		font-size: 14px;
		line-height: 20px;
		max-height: calc(20px * 3 + 16px);
		transition: height 0.12s ease;
	}

	.send-btn {
		background: #030d26;
		color: #fff;
		padding: 8px 16px;
		border: none;
		border-radius: 3px;
		cursor: pointer;
		margin-left: 8px;
		font-size: 14px;
	}

	.send-btn:hover {
		background: #020a1d;
	}
</style>